import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:syria_sports/data/controllers/profile_controller.dart';
import '../../../../data/models/auth/user.dart';
import '/core/app_export.dart';
part 'player_profile_event.dart';
part 'player_profile_state.dart';

/// A bloc that manages the state of a Profile according to the event that is dispatched to it.
class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
  ProfileBloc(ProfileState initialState) : super(initialState) {
    on<ProfileInitialEvent>(_onInitialize);
    on<GetProfileEvent>(_onGetProfile);
    on<UpdatePlayerStateEvent>(_updatePlayerState);
  }

  _onInitialize(
    ProfileInitialEvent event,
    Emitter<ProfileState> emit,
  ) async {
    if(state.user == null){
      add(GetProfileEvent());
    }else{
      emit(state.gotData(user: state.user!));
    }
  }

  _onGetProfile(
      GetProfileEvent event,
      Emitter<ProfileState> emit,
    )async{
    emit(state.hasLoading());
    await ProfileController.getMyProfile().then((value) {
      if(value?.data == null){
        emit(state.hasError(error: value?.message));
        return ;
      }
      User user = User.fromJson(value!.data);
      emit(state.gotData(user: user));
    }).catchError((e){
      emit(state.hasError(error : 'حدث خطأ اثناء معالجة البيانات'));
    });

  }

  _updatePlayerState(
      UpdatePlayerStateEvent event,
      Emitter<ProfileState> emit,
      )async{
    emit(state.copyWith(user: event.user));
  }

}
